import dotenv from 'dotenv';
dotenv.config();
console.error('MCP_PYTHON_EXE:', process.env.MCP_PYTHON_EXE);
/**
 * @author zoulei
 * MCP服务器主入口文件
 * 用于连接达梦数据库并提供MCP协议接口
 */

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { 
  CallToolRequestSchema, 
  ListToolsRequestSchema,
  Tool
} from '@modelcontextprotocol/sdk/types.js';
import axios from 'axios';
import net from 'net';
import { pythonServiceManager } from './pythonServiceManager.js';

// 创建MCP服务器
const server = new Server({
  name: 'MCP Server',
  version: '1.0.0',
  capabilities: {
    tools: {},
  },
});

// 工具定义
const tools: Tool[] = [
  {
    name: 'dm_query',
    description: '执行达梦数据库SQL查询',
    inputSchema: {
      type: 'object',
      properties: {
        sql: {
          type: 'string',
          description: '要执行的SQL查询语句'
        }
      },
      required: ['sql']
    }
  },
  {
    name: 'dm_execute',
    description: '执行达梦数据库SQL更新操作（INSERT、UPDATE、DELETE、DDL）。禁止DROP/TRUNCATE操作，DELETE语句必须包含WHERE条件，否则可通过参数where补充。',
    inputSchema: {
      type: 'object',
      properties: {
        sql: {
          type: 'string',
          description: '要执行的SQL更新语句'
        },
        where: {
          type: 'string',
          description: 'DELETE语句可选的WHERE条件（如未在SQL中指定）',
        }
      },
      required: ['sql']
    }
  },
  {
    name: 'dm_tables',
    description: '获取达梦数据库中的所有表信息',
    inputSchema: {
      type: 'object',
      properties: {}
    }
  },
  {
    name: 'dm_table_info',
    description: '获取指定表的详细信息（列、索引、备注等）',
    inputSchema: {
      type: 'object',
      properties: {
        tableName: {
          type: 'string',
          description: '表名'
        },
        schema: {
          type: 'string',
          description: '模式名（可选，ALL视图下可指定）',
        }
      },
      required: ['tableName']
    }
  },
  {
    name: 'dm_connect',
    description: '连接到达梦数据库',
    inputSchema: {
      type: 'object',
      properties: {
        host: {
          type: 'string',
          description: '数据库主机地址'
        },
        port: {
          type: 'number',
          description: '数据库端口'
        },
        username: {
          type: 'string',
          description: '用户名'
        },
        password: {
          type: 'string',
          description: '密码'
        }
      },
      required: ['host', 'port', 'username', 'password']
    }
  },
  {
    name: 'ping_server',
    description: '检测数据库服务器地址和端口的网络连通性',
    inputSchema: {
      type: 'object',
      properties: {
        host: {
          type: 'string',
          description: '服务器地址（默认使用config.dm.host）'
        },
        port: {
          type: 'number',
          description: '服务器端口（默认使用config.dm.port）'
        }
      },
      required: []
    }
  },
  {
    name: 'dm_code_value_query',
    description: '查询code_value表的二级代码，支持多条件组合和分页（每页1000行，page参数可选）',
    inputSchema: {
      type: 'object',
      properties: {
        codetype: { type: 'string', description: '代码类别编码，可选' },
        codename: { type: 'string', description: '代码名称，模糊匹配，可选' },
        codevalue: { type: 'string', description: '代码值，可选' },
        parent: { type: 'string', description: '父级代码值，可选' },
        page: { type: 'integer', description: '页码，默认1', minimum: 1 }
      },
      required: []
    }
  },
];

// 注册工具列表处理器
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools
  };
});

// 注册工具调用处理器
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  try {
    switch (name) {
      case 'dm_connect':
        return await handleConnect(args);
      case 'dm_query':
        return await handleQuery(args);
      case 'dm_execute':
        return await handleExecute(args);
      case 'dm_tables':
        return await handleTables();
      case 'dm_table_info':
        return await handleTableInfo(args);
      case 'ping_server':
        return await handlePingServer(args);
      case 'dm_code_value_query':
        return await handleCodeValueQuery(args);
      default:
        return {
          content: [
            { type: 'text', text: `未知的工具: ${name}` }
          ]
        };
    }
  } catch (error) {
    // 兜底：所有异常都用普通文本返回，避免 Cursor 红点
    return {
      content: [
        { type: 'text', text: `发生异常: ${error instanceof Error ? error.message : String(error)}` }
      ]
    };
  }
});

/**
 * 处理数据库连接（已废弃，实际连接由Python服务管理）
 */
async function handleConnect(args: any) {
  try {
    return {
      content: [
        {
          type: 'text',
          text: `连接到达梦数据库（参数见 Python 服务配置）已移至 Python 服务`
        }
      ]
    };
  } catch (error) {
    throw new Error(`连接失败: ${error instanceof Error ? error.message : String(error)}`);
  }
}

/**
 * 处理SQL查询请求，转发到Python服务
 * @param args { sql: string }
 */
async function handleQuery(args: any) {
  const { sql } = args;
  const resp = await axios.post(`${pythonServiceManager.getServiceUrl()}/query`, { sql });
  if (resp.data.message) {
    return { content: [ { type: 'text', text: resp.data.message } ] };
  }
  return {
    content: [
      {
        type: 'text',
        text: `查询结果:\n${JSON.stringify(resp.data, null, 2)}`
      }
    ]
  };
}

/**
 * 处理SQL更新请求，转发到Python服务
 * @param args { sql: string }
 */
async function handleExecute(args: any) {
  const { sql } = args;
  const resp = await axios.post(`${pythonServiceManager.getServiceUrl()}/execute`, { sql });
  if (resp.data.message) {
    return { content: [ { type: 'text', text: resp.data.message } ] };
  }
  return {
    content: [
      {
        type: 'text',
        text: `执行成功，影响行数: ${resp.data.affectedRows}`
      }
    ]
  };
}

/**
 * 获取所有表名，转发到Python服务
 */
async function handleTables() {
  const resp = await axios.get(`${pythonServiceManager.getServiceUrl()}/tables`);
  if (resp.data.message) {
    return { content: [ { type: 'text', text: resp.data.message } ] };
  }
  return {
    content: [
      {
        type: 'text',
        text: `数据库表列表:\n${JSON.stringify(resp.data, null, 2)}`
      }
    ]
  };
}

/**
 * 获取指定表结构，转发到Python服务
 * @param args { tableName: string, schema?: string }
 */
async function handleTableInfo(args: any) {
  const { tableName, schema } = args;
  const resp = await axios.post(`${pythonServiceManager.getServiceUrl()}/table_info`, { tableName, schema });
  if (resp.data.message) {
    return { content: [ { type: 'text', text: resp.data.message } ] };
  }
  return {
    content: [
      {
        type: 'text',
        text: `表 ${schema ? schema + '.' : ''}${tableName} 的详细信息:\n${JSON.stringify(resp.data, null, 2)}`
      }
    ]
  };
}

/**
 * 检查数据库服务器地址和端口的网络连通性
 * @param args { host?: string, port?: number }
 */
async function handlePingServer(args: any): Promise<any> {
  const host = args.host || '127.0.0.1';
  const port = args.port || 5001;
  return new Promise((resolve) => {
    const socket = new net.Socket();
    let isDone = false;
    const onResult = (ok: boolean, msg: string) => {
      if (!isDone) {
        isDone = true;
        socket.destroy();
        resolve({
          content: [
            {
              type: 'text',
              text: ok ? `服务器 ${host}:${port} 可达 @author zoulei` : `服务器 ${host}:${port} 不可达: ${msg} @author zoulei`
            }
          ]
        });
      }
    };
    socket.setTimeout(3000);
    socket.on('connect', () => onResult(true, ''));
    socket.on('timeout', () => onResult(false, '连接超时'));
    socket.on('error', (err: Error) => onResult(false, err.message));
    socket.connect(port, host);
  });
}

/**
 * 处理code_value二级代码查询，转发到Python服务
 * @param args { codetype?: string, codename?: string, codevalue?: string, parent?: string, page?: number }
 * 支持分页，每页1000行，page参数可选
 */
async function handleCodeValueQuery(args: any) {
  // 校验至少有一个入参
  if (!args.codetype && !args.codename && !args.codevalue && !args.parent) {
    return {
      content: [
        { type: 'text', text: '至少需要一个查询条件' }
      ]
    };
  }
  const resp = await axios.post(`${pythonServiceManager.getServiceUrl()}/code_value_query`, args);
  if (resp.data.message) {
    return { content: [ { type: 'text', text: resp.data.message } ] };
  }
  return {
    content: [
      { type: 'text', text: `查询结果(分页):\n${JSON.stringify(resp.data, null, 2)}` }
    ]
  };
}

// 启动服务器
async function main() {
  // 启动Python服务
  await pythonServiceManager.start();
  const transport = new StdioServerTransport();
  
  // 监听stdio连接状态
  let isConnected = true;
  
  // 监听stdin的end事件，表示Cursor关闭了连接
  process.stdin.on('end', async () => {
    if (isConnected) {
      isConnected = false;
      console.error('end事件检测到Cursor关闭连接，正在清理资源...');
      console.error('准备退出...');
      process.exit(0);
    }
  });
  
  
  await server.connect(transport);
  console.error('MCP服务器已启动');
  console.error('Node.js version:', process.version, 'arch:', process.arch);
  
  
}



// 保留操作系统信号监听作为兜底机制
process.on('SIGTERM', async () => {
  console.error('收到SIGTERM信号，正在关闭Python服务...');
  await pythonServiceManager.stop();
  process.exit(0);
});

process.on('SIGINT', async () => {
  console.error('收到SIGINT信号，正在关闭Python服务...');
  await pythonServiceManager.stop();
  process.exit(0);
});



main().catch(console.error); 